/**
 * @file
 * @author Ivan Babushkin (jogrms@gmail.com)
 * @date 13.06.2010
 */

#include <cmdedit.h>
#include <QPalette>
#include <QKeyEvent>
#include <QDebug>
#include <QFile>

CmdEdit::CmdEdit(QWidget *parent) :QLineEdit(parent) {
}

CmdEdit::~CmdEdit() {
}

void CmdEdit::applySettings(struct QOSettings *settings) {
	setFrame(settings->cmdEditFrame);
	QPalette tmp = palette();
	tmp.setColor(QPalette::Base, settings->cmdEditBgColor);
	setPalette(tmp);
	historyCount = settings->cmdEditHistory;
}

void CmdEdit::showPreviousCommand() {
	if (cmdList.isEmpty()) {
		return;
	}
	if (cmdIterator != cmdList.begin()) {
		cmdIterator--;
		setText(*cmdIterator);
	}
}

void CmdEdit::showNextCommand() {
	if (cmdList.isEmpty()) {
		return;
	}
	if (cmdIterator < cmdList.end() - 1) {
		cmdIterator++;
		setText(*cmdIterator);
	}
	else if (cmdIterator == cmdList.end() - 1) {
		cmdIterator++;
		setText(currentCmd);
	}
}

void CmdEdit::keyPressEvent(QKeyEvent *event) {
	switch (event->key()) {
		case Qt::Key_Up:
//			if ((cmdModified) && (cmdIterator == cmdList.end())) {
//				currnetCmd = text();
//				cmdIterator = cmdList.end();
//			}
			showPreviousCommand();
//			cmdModified = false;
			break;

		case Qt::Key_Down:
			showNextCommand();
//			cmdModified = false;
			break;

		case Qt::Key_Enter:
		case Qt::Key_Return:
			cmdList << text();
			if (cmdList.count() > historyCount) {
				cmdList.removeFirst();
			}
			cmdIterator = cmdList.end();
			break;

		default:
			if (cmdIterator == cmdList.end()) {
				currentCmd = text();
			}
//			cmdModified = true;
			break;
	}
	QLineEdit::keyPressEvent(event);
	event->accept();
}

void CmdEdit::showEvent(QShowEvent *event) {
//	cmdModified = true;
	currentCmd = text();
	cmdIterator = cmdList.end();
	QLineEdit::showEvent(event);
}

void CmdEdit::saveHistory(QString fileName) {
	QFile file(fileName);
	if (file.open(QFile::WriteOnly | QFile::Truncate)) {
		QTextStream out(&file);
		out << cmdList.join("\n");
	}
	file.close();
}

void CmdEdit::loadHistory(QString fileName) {
	QFile file(fileName);
	if (file.open(QFile::ReadOnly | QFile::Text)) {
		QTextStream in(&file);
		QString str = in.readAll();
		cmdList = str.split("\n");
	}
	while (cmdList.count() > historyCount) {
		cmdList.removeFirst();
	}
}
